/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package View;


import View.Model.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;


/**
 *
 * @author ANA
 */
public class NewProject extends javax.swing.JFrame {
    JTree novaArvore;
    /**
     * Creates new form NewProject
     */
    Project project;
    public NewProject(JTree novaArvore, Project project) {
        this.project = project; 
        this.novaArvore = novaArvore;
        initComponents();
        
    }
    

        
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtProjectName = new javax.swing.JTextField();
        txtProjectFolder = new javax.swing.JTextField();
        btnBrowse = new javax.swing.JButton();
        btnOk = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("New Project");

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jLabel1.setText("New Project");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel2.setText("Project Name:");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        jLabel3.setText("Project Folder:");

        txtProjectName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProjectNameActionPerformed(evt);
            }
        });

        txtProjectFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProjectFolderActionPerformed(evt);
            }
        });

        btnBrowse.setText("Browser");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        btnOk.setText("OK");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(txtProjectName, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtProjectFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(14, 14, 14)
                                        .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBrowse))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(172, 172, 172)
                        .addComponent(jLabel1)))
                .addContainerGap(12, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(txtProjectName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtProjectFolder, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBrowse))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOk)
                    .addComponent(btnCancel))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
   
    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        // TODO add your handling code here:
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int dialogVal = jfc.showOpenDialog(null);
        if (dialogVal == JFileChooser.APPROVE_OPTION){
            project.setProjectFolder(jfc.getSelectedFile().getAbsolutePath());
            txtProjectFolder.setText(project.getProjectFolder());
        }
    }//GEN-LAST:event_btnBrowseActionPerformed
    
    private void txtProjectFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProjectFolderActionPerformed
        // TODO add your handling code here:
        //t.setText(directoryPath);
    }//GEN-LAST:event_txtProjectFolderActionPerformed

    private void txtProjectNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProjectNameActionPerformed
        // TODO add your handling code here:
       
    }//GEN-LAST:event_txtProjectNameActionPerformed

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        // TODO add your handling code here:
        //project = new Project(txtProjectName.getText(),txtProjectFolder.getText());
        
        project.setProjectNome(txtProjectName.getText());
        //project.setProjectNome(String.format("<<Project>> %s",txtProjectName.getText()));
        project.setProjectFolder(txtProjectFolder.getText());
        project.setNomeServer("servertest");
        project.setNomeProt("protocoltest");
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(String.format("<<Project>> %s",project.getProjectNome()));
        DefaultTreeModel newModel;
        rootNode.add(new DefaultMutableTreeNode(String.format("<<Protocol>> Mqtt %s",project.getNomeProt())));
        rootNode.add(new DefaultMutableTreeNode(String.format("<<Server>> Web %s",project.getNomeServer())));
        newModel = new DefaultTreeModel(rootNode);
        novaArvore.setModel(newModel);
        insereActions(rootNode, project);
        this.setVisible(false);
        
        File f1 = new File(project.getProjectFolder(), project.getProjectNome());
        if (!f1.mkdir()){
            System.err.println("Erro. O diretório já existe");
        }                                
                
        // save in JSON file
        
        //String aux = project.getProjectFolder() + File.separator + project.getProjectNome() + File.separator + "project.json";
        
        String aux = txtProjectFolder.getText() + File.separator + project.getProjectNome() + File.separator + "project.json";

        
        System.out.println(project.getProjectNome());
        System.out.println(aux);
        System.out.println(project.getProjectFolder());
        
        //JSONObject objetoJson = new JSONObject();
        //objetoJson.put("projectNome", project.getProjectNome());
        //objetoJson.put("projectFolder", project.getProjectFolder());
        
        FileWriter writeFile;
        try {
            writeFile = new FileWriter(aux);
            //writeFile.write(objetoJson.toString());
            writeFile.close();
        } catch (IOException ex) {
            Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
        }
        super.dispose();
    }//GEN-LAST:event_btnOkActionPerformed
    
    public void insereActions(DefaultMutableTreeNode rootNode, Project novoProject){
        DefaultTreeModel treeModel = (DefaultTreeModel)novaArvore.getModel();
        treeModel.setRoot(rootNode);
        novaArvore.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent me) {
                JPopupMenu popupMenu = new JPopupMenu();
                JMenuItem createNewThing = new JMenuItem("Create new Thing");
                JMenuItem createNewComponent = new JMenuItem("Create new component");
                JMenuItem createNewController = new JMenuItem("Create new controller");
                JMenuItem createNewTopic = new JMenuItem("Create new Topic");
                JMenuItem createNewPort = new JMenuItem("Create new Port");
                JMenuItem editProtocol = new JMenuItem("Edit Protocol");
                JMenuItem editServer = new JMenuItem("Edit Server");
                TreePath tp = novaArvore.getPathForLocation(me.getX(), me.getY());
                String [] value = tp.getLastPathComponent().toString().split(" ");
                novaArvore.remove(popupMenu);
                novaArvore.setComponentPopupMenu(popupMenu);
                if(SwingUtilities.isRightMouseButton(me)){
                    createNewComponent.removeAll();
                    createNewController.removeAll();
                    createNewThing.removeAll();
                    switch (value[0].trim()) {
                        case "<<Thing>>":
                            createNewComponent.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isProject(selectedNode) || novoProject.isThing(selectedNode)) {
                                    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("<<Component>> Name");
                                    treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
                                }
                            }});
                            createNewController.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                    if (novoProject.isThing(selectedNode)) {
                                        controllerMenuItemActionPerformed(e);
                                    }
                                }
                            });
                            popupMenu.add(createNewComponent);
                            popupMenu.add(createNewController);
                            novaArvore.setComponentPopupMenu(popupMenu);
                        break;
                        case "<<Component>>":
                            novaArvore.remove(popupMenu);
                            createNewPort.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isComponent(selectedNode)) {
                                    portaMenuItemActionPerformed(e);
                                }
                            }});
                            createNewTopic.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isComponent(selectedNode)) {
                                    topicMenuItemActionPerformed(e);
                                }
                            }});
                            popupMenu.add(createNewPort);
                            popupMenu.add(createNewTopic);
                            novaArvore.setComponentPopupMenu(popupMenu);
                            novaArvore.getComponentPopupMenu();
                        break;
                        case "<<Controller>>":
                            novaArvore.remove(popupMenu);
                            createNewPort.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isController(selectedNode)) {
                                    portaMenuItemActionPerformed(e);
                                }
                            }});
                            popupMenu.add(createNewPort);
                            novaArvore.setComponentPopupMenu(popupMenu);
                            novaArvore.getComponentPopupMenu();
                        break;
                        case "<<Project>>":
                            novaArvore.remove(popupMenu);
                            createNewThing.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isProject(selectedNode) || novoProject.isThing(selectedNode)) {
                                    thingMenuItemActionPerformed(e);
                                }
                            }
                            });
                            popupMenu.add(createNewThing);
                            novaArvore.setComponentPopupMenu(popupMenu);
                            novaArvore.getComponentPopupMenu();
                        break;
                        case "<<Protocol>>":
                            novaArvore.remove(popupMenu);
                            editProtocol.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isProtocol(selectedNode)) {
                                    protocolMenuItemActionPerformed(e);
                                }
                            }});
                            popupMenu.add(editProtocol);
                            novaArvore.setComponentPopupMenu(popupMenu);
                            novaArvore.getComponentPopupMenu();
                        break;
                        case "<<Server>>":
                            novaArvore.remove(popupMenu);
                            editServer.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) novaArvore.getLastSelectedPathComponent();
                                if (novoProject.isServer(selectedNode)) {
                                    serverMenuItemActionPerformed(e);
                                }
                            }});
                            popupMenu.add(editServer);
                            novaArvore.setComponentPopupMenu(popupMenu);
                            novaArvore.getComponentPopupMenu();
                        break;
                    }
                }
        }});
    }

    
    private void thingMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ThingPage tela = new ThingPage(novaArvore);
        tela.setVisible(true);
    }               

    private void controllerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ControllerPage tela = new ControllerPage(novaArvore);
        tela.setVisible(true);
    }                                              

    private void portaMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        PortPage tela = new PortPage(novaArvore);
        tela.setVisible(true);
    }                                              

    private void topicMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        TopicPage tela = new TopicPage(novaArvore);
        tela.setVisible(true);
    }                                              

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        super.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void protocolMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverMenuItemActionPerformed
        // TODO add your handling code here:
        ProtocolPage tela = new ProtocolPage(novaArvore);
        tela.setVisible(true);
    }//GEN-LAST:event_serverMenuItemActionPerformed

    private void serverMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
        ServerPage tela = new ServerPage(novaArvore);
        tela.setVisible(true);
    }//GEN
    /**
     * @param args the command line arguments
     */
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOk;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField txtProjectFolder;
    private javax.swing.JTextField txtProjectName;
    // End of variables declaration//GEN-END:variables
}
